import {createRouter,createWebHashHistory,createWebHistory} from "vue-router"

//定义路由配置
import login from "../components/Login"
import home from "../components/Home"
import activity from "../components/Activity"
import game from "../components/Game"
import personalcenter from "../components/PersonalCenter"
import talk from "../components/Talk"
import chatroom from "../components/ChatRoom"
import templefair from "../components/TempleFair"
import posttalk from "../components/PostTalk"
import detail from "../components/Detail"
import store from "@/store"

const routes = [
    {
        path: "/",
        redirect: "/home"
    },
    {
        path: "/login",
        component: login,
    },
    {
        path: "/home",
        component: home,
        redirect: "/activity",
        meta:{
            requireAuth: true
        },
        children: [
            {
                path: "/activity",
                component: activity,
            },
            {
                path: "/game",
                component: game
            },
            {
                path: "/personalcenter",
                component: personalcenter
            },
            {
                path: "/talk",
                component: talk
            },
            {
                path: "/chatroom",
                component: chatroom
            },
            {
                path: "/templefair",
                component: templefair
            },
            {
                path: "/posttalk",
                component: posttalk
            },
            {
                
                path: "/detail",
                component: detail
            }
        ]
    },
    
];

//创建路由实例
const router = createRouter({
    //采用hash模式
    history: createWebHashHistory(),
    //使用上方定义的路由配置
    routes,
});


// 路由前置守卫
router.beforeEach(async (to,from) => {
    console.log("to",to,"from",from)
    if(!localStorage.getItem("token") && to.path != '/login'){
        console.log('token已过期')
        return '/login'
    }
    if(localStorage.getItem('token') && to.path == '/login'){
        return '/home'
    }
    
    if(to.meta.requireAuth){
        if(localStorage.getItem("token")){
            //不要跟路径，不然路由一直跳，无限重定向
            return 
        }else{
            return '/login'
        }
    }
})

export default router